package com.enqualcomm.kids.mvp.weather;

import android.support.v4.util.SimpleArrayMap;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.enqualcomm.kids.bean.CityInfo;
import com.enqualcomm.kids.bean.RecentWeather;
import com.enqualcomm.kids.bean.Weather;
import com.enqualcomm.kids.component.MyApplication;
import com.enqualcomm.kids.network.BaiduApiRequest;
import com.enqualcomm.kids.network.Parser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;

import common.utils.GsonFactory;
import common.utils.MyLogger;

/**
 * Created by yinzhiqun on 2015/10/13.
 *
 */
public class BaiduApiWeatherModel implements IWeatherModel {

    private final RequestQueue requestQueue;
    SimpleArrayMap<String, String> dict;
    private boolean cancelAllTask;

    public BaiduApiWeatherModel() {
        requestQueue = MyApplication.getInstance().getHttpRequestQueue();
        dict = new SimpleArrayMap<>();
    }

    private void queryCityInfo(final String cityName, final WeatherEventHandler handler, final boolean today) {
        String cityNameUrl = null;
        try {
            cityNameUrl = URLEncoder.encode(cityName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://apis.baidu.com/apistore/weatherservice/cityinfo?cityname=" + cityNameUrl;
        BaiduApiRequest baiduApiRequest = new BaiduApiRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    CityInfo cityInfo = new Gson().fromJson(response, CityInfo.class);
                    if (cityInfo.errNum == 0) {
                        dict.put(cityName, cityInfo.retData.cityCode);//保存城市名和城市id的对应关系

                        if (!cancelAllTask) {//如果退出了，不应该继续联网
                            if (today) {
                                queryWeatherByCityId(cityInfo.retData.cityCode, handler);
                            } else {
                                queryRecentweathersByIdAndName(cityInfo.retData.cityCode, cityName, handler);
                            }
                        }
                    } else {
                        handler.onError();
                    }
                }catch (Exception e){//错误返回和正确返回不是一个类型~
                    e.printStackTrace();
                    handler.onError();
                }

            }
        }, null);
        baiduApiRequest.setTag(this);
        requestQueue.add(baiduApiRequest);
    }

    private void queryWeatherByCityId(String cityId, final WeatherEventHandler handler) {
        String url = "http://apis.baidu.com/apistore/weatherservice/cityid?cityid=" + cityId;
        BaiduApiRequest baiduApiRequest = new BaiduApiRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    Weather weather = new Gson().fromJson(response, Weather.class);
                    if (weather.errNum == 0) {
                        handler.onSuccessGetTodayWeather(weather);
                    } else {
                        handler.onError();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    handler.onError();
                }
            }
        }, null);
        baiduApiRequest.setTag(this);
        requestQueue.add(baiduApiRequest);
    }


    private void queryWeatherByCityName(String cityName, final WeatherEventHandler handler) {
        String cityNameUrl = null;
        try {
            cityNameUrl = URLEncoder.encode(cityName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://apis.baidu.com/apistore/weatherservice/cityname?cityname=" + cityNameUrl;
        BaiduApiRequest baiduApiRequest = new BaiduApiRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try{
                    Weather weather = new Gson().fromJson(response, Weather.class);
                    if (weather.errNum == 0) {
                        handler.onSuccessGetTodayWeather(weather);
                    } else {
                        handler.onError();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    handler.onError();
                }
            }
        }, null);
        baiduApiRequest.setTag(this);
        requestQueue.add(baiduApiRequest);
    }


    private void queryRecentweathersByIdAndName(String cityId, String cityName, final WeatherEventHandler handler) {
        String cityNameUrl = null;
        try {
            cityNameUrl = URLEncoder.encode(cityName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://apis.baidu.com/apistore/weatherservice/recentweathers?cityname="
                + cityNameUrl + "&cityid=" + cityId;
        BaiduApiRequest baiduApiRequest = new BaiduApiRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    RecentWeather Weather = new Gson().fromJson(response, RecentWeather.class);
                    if (Weather.errNum == 0) {
                        handler.onSuccessGetRecentWeather(Weather);
                    } else {
                        handler.onError();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    handler.onError();
                }
            }
        }, null);
        baiduApiRequest.setTag(this);
        requestQueue.add(baiduApiRequest);
    }

    private String[] hk_weathers = {
            "{\"city\":\"香港\",\"h_tmp\":\"25\",\"l_tmp\":\"21\",\"temp\":\"25\",\"weather\":\"阵雨\",\"curTemp\":\"25\",\"type\":\"阵雨\",\"date\":\"2016-04-14\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"27\",\"l_tmp\":\"22\",\"temp\":\"22\",\"weather\":\"阴\",\"curTemp\":\"22\",\"type\":\"阴\",\"date\":\"2016-04-15\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"28\",\"l_tmp\":\"23\",\"temp\":\"24\",\"weather\":\"阴\",\"curTemp\":\"24\",\"type\":\"阴\",\"date\":\"2016-04-16\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"27\",\"l_tmp\":\"21\",\"temp\":\"22\",\"weather\":\"小雨\",\"curTemp\":\"22\",\"type\":\"小雨\",\"date\":\"2016-04-17\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"24\",\"l_tmp\":\"21\",\"temp\":\"22\",\"weather\":\"雷阵雨\",\"curTemp\":\"22\",\"type\":\"雷阵雨\",\"date\":\"2016-04-18\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"24\",\"l_tmp\":\"21\",\"temp\":\"21\",\"weather\":\"阵雨\",\"curTemp\":\"21\",\"type\":\"阵雨\",\"date\":\"2016-04-19\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"25\",\"l_tmp\":\"22\",\"temp\":\"23\",\"weather\":\"多云\",\"curTemp\":\"23\",\"type\":\"多云\",\"date\":\"2016-04-20\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"28\",\"l_tmp\":\"22\",\"temp\":\"24\",\"weather\":\"多云\",\"curTemp\":\"24\",\"type\":\"多云\",\"date\":\"2016-04-21\"}",

            "{\"city\":\"香港\",\"h_tmp\":\"26\",\"l_tmp\":\"23\",\"temp\":\"25\",\"weather\":\"多云\",\"curTemp\":\"25\",\"type\":\"多云\",\"date\":\"2016-04-22\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"27\",\"l_tmp\":\"23\",\"temp\":\"26\",\"weather\":\"多云\",\"curTemp\":\"26\",\"type\":\"多云\",\"date\":\"2016-04-23\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"29\",\"l_tmp\":\"24\",\"temp\":\"29\",\"weather\":\"晴\",\"curTemp\":\"29\",\"type\":\"晴\",\"date\":\"2016-04-24\"}",
            "{\"city\":\"香港\",\"h_tmp\":\"29\",\"l_tmp\":\"25\",\"temp\":\"28\",\"weather\":\"晴\",\"curTemp\":\"28\",\"type\":\"晴\",\"date\":\"2016-04-25\"}",
    };

    @Override
    public void queryWeatherToday(String cityName, WeatherEventHandler handler) {
        if (cityName.startsWith("香港")){
            int i = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)-14;
            if (i>=0&&i<hk_weathers.length){
                Weather weather = new Weather();
                weather.retData = GsonFactory.newInstance().fromJson(hk_weathers[i], Weather.RetData.class);
                handler.onSuccessGetTodayWeather(weather);
                return;
            }
        }


      /*  String cityId = dict.get(cityName); 傻逼百度api，根据id查不到，根据名字可以查到
        if (cityId == null) {
            //联网获取
            queryCityInfo(cityName, handler, true);
        } else {
            //直接查询
            queryWeatherByCityId(cityId, handler);
        }*/
        queryWeatherByCityName(cityName, handler);
    }

    @Override
    public void queryWeatherRecent(String cityName, WeatherEventHandler handler) {
        if (cityName.startsWith("香港")){
            int i = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)-14;
            if (i>=0&&i<hk_weathers.length-4){
                RecentWeather recentWeather = new RecentWeather();
                recentWeather.retData = new RecentWeather.RetData();
                recentWeather.retData.city = "香港";
                recentWeather.retData.today = GsonFactory.newInstance().fromJson(hk_weathers[i],RecentWeather.Today.class);
                recentWeather.retData.forecast = new ArrayList<>();
                for (int j = i; j < i+4; j++) {
                    RecentWeather.Forecast forecast = GsonFactory.newInstance().fromJson(hk_weathers[j], RecentWeather.Forecast.class);
                    recentWeather.retData.forecast.add(forecast);
                }

//                MyLogger.jLog().i(hk_weathers[i]);
                handler.onSuccessGetRecentWeather(recentWeather);
                return;
            }
        }

        //查询最近7天的天气
        String cityId = dict.get(cityName);
        if (cityId == null) {
            //联网获取
            queryCityInfo(cityName, handler, false);
        } else {
            //直接查询
            queryRecentweathersByIdAndName(cityId, cityName, handler);
        }

    }

    @Override
    public void onStop() {
        cancelAllTask = true;
        requestQueue.cancelAll(this);
    }


}
